package xh.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpRequest;
import xh.server.processors.AjaxRequestProcessor;
import xh.server.processors.LongPollingProcessor;
import xh.server.processors.PlayerRelateProcessor;
import xh.server.processors.StaticResourceProcessor;
import xh.util.Global;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * Created by Administrator on 2016/6/25.
 */
public class RequestDispatcher {


    public RequestProcessor dispatch(HttpRequest requestHead, HttpContent content, ChannelHandlerContext ctx) {

        String uri = null;
        try {
            uri = URLDecoder.decode(requestHead.getUri(), Global.DefaultCharset.name());
        } catch (UnsupportedEncodingException e) {
        }


        String[] names = parseNames(uri);

        if (names == null) {
            return null;
        }

        RequestProcessor requestProcessor = null;

        if (names[0].equals("player")) {
            PlayerRelateProcessor p = new PlayerRelateProcessor(names[1]);
            p.parseCmd();
            requestProcessor = p;

        } else if (names[0].equals("ajax")) {
            AjaxRequestProcessor aj = new AjaxRequestProcessor(names[1]);
            requestProcessor = aj;

        } else if (names[0].equals("longPolling")) {
            LongPollingProcessor p = new LongPollingProcessor(ctx, names[1]);
            requestProcessor = p;

        } else if (names[0].equals("statics")) {
            StaticResourceProcessor s = new StaticResourceProcessor(names[1]);
            requestProcessor = s;
        }

        if (requestProcessor != null) {
            requestProcessor.setHttpRequest(requestHead, content);
        }

        return requestProcessor;
    }


    private String[] parseNames(String uri) {
        if (uri.startsWith("/")) {
            uri = uri.substring(1);
        }

        int p = uri.indexOf("/");
        if (p > 0) {
            return new String[]{uri.substring(0, p), uri.substring(p + 1)};
        }

        return null;
    }
}
